<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  Col,
  Form,
  FormItem,
  Input,
  message,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import StatisticsCard from '#/components/hotel/StatisticsCard.vue';

// 清洁任务状态枚举
enum CleaningTaskStatus {
  ASSIGNED = 'assigned',
  CANCELLED = 'cancelled',
  COMPLETED = 'completed',
  PENDING = 'pending',
  PROCESSING = 'processing',
}

// 响应式数据
const loading = ref(false);
const showAddModal = ref(false);

// 搜索表单
const searchForm = reactive({
  roomNumber: '',
  type: '',
  status: '',
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) =>
    `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
});

// 任务数据
const tasks = ref([
  {
    id: '1',
    roomNumber: '101',
    type: 'regular',
    status: CleaningTaskStatus.PROCESSING,
    priority: 'medium',
    assignedTo: '张阿姨',
    plannedDate: dayjs(),
    plannedTime: '09:00',
    requirements: '日常清洁，重点卫生间',
  },
  {
    id: '2',
    roomNumber: '201',
    type: 'checkout',
    status: CleaningTaskStatus.ASSIGNED,
    priority: 'high',
    assignedTo: '李阿姨',
    plannedDate: dayjs(),
    plannedTime: '10:00',
    requirements: '退租深度清洁',
  },
  {
    id: '3',
    roomNumber: '301',
    type: 'deep',
    status: CleaningTaskStatus.COMPLETED,
    priority: 'medium',
    assignedTo: '王阿姨',
    plannedDate: dayjs().subtract(1, 'day'),
    plannedTime: '08:00',
    requirements: '深度清洁，包括家具',
  },
]);

// 统计信息
const statistics = computed(() => {
  const totalTasks = tasks.value.length;
  const pendingTasks = tasks.value.filter(
    (t) => t.status === CleaningTaskStatus.PENDING,
  ).length;
  const processingTasks = tasks.value.filter(
    (t) => t.status === CleaningTaskStatus.PROCESSING,
  ).length;
  const completedTasks = tasks.value.filter(
    (t) => t.status === CleaningTaskStatus.COMPLETED,
  ).length;

  return {
    totalTasks,
    pendingTasks,
    processingTasks,
    completedTasks,
  };
});

// 过滤后的任务
const filteredTasks = computed(() => {
  let result = tasks.value;

  if (searchForm.roomNumber) {
    result = result.filter((t) => t.roomNumber.includes(searchForm.roomNumber));
  }
  if (searchForm.type) {
    result = result.filter((t) => t.type === searchForm.type);
  }
  if (searchForm.status) {
    result = result.filter((t) => t.status === searchForm.status);
  }

  return result;
});

// 表格列定义
const columns = [
  {
    title: '房间号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
    width: 100,
  },
  {
    title: '清洁类型',
    dataIndex: 'type',
    key: 'type',
    width: 120,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    key: 'priority',
    width: 100,
  },
  {
    title: '分派给',
    dataIndex: 'assignedTo',
    key: 'assignedTo',
    width: 120,
  },
  {
    title: '计划时间',
    dataIndex: 'plannedTime',
    key: 'plannedTime',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
];

// 工具函数
const getTaskStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    [CleaningTaskStatus.PENDING]: 'orange',
    [CleaningTaskStatus.ASSIGNED]: 'blue',
    [CleaningTaskStatus.PROCESSING]: 'processing',
    [CleaningTaskStatus.COMPLETED]: 'success',
    [CleaningTaskStatus.CANCELLED]: 'default',
  };
  return colorMap[status] || 'default';
};

const getTaskStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    [CleaningTaskStatus.PENDING]: '待处理',
    [CleaningTaskStatus.ASSIGNED]: '已分派',
    [CleaningTaskStatus.PROCESSING]: '进行中',
    [CleaningTaskStatus.COMPLETED]: '已完成',
    [CleaningTaskStatus.CANCELLED]: '已取消',
  };
  return statusMap[status] || status;
};

const getTaskTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    regular: 'blue',
    checkout: 'orange',
    deep: 'purple',
    emergency: 'red',
  };
  return colorMap[type] || 'default';
};

const getTaskTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    regular: '定期清洁',
    checkout: '退租清洁',
    deep: '深度清洁',
    emergency: '紧急清洁',
  };
  return typeMap[type] || type;
};

const getPriorityColor = (priority: string) => {
  const colorMap: Record<string, string> = {
    low: 'default',
    medium: 'orange',
    high: 'red',
  };
  return colorMap[priority] || 'default';
};

const getPriorityText = (priority: string) => {
  const priorityMap: Record<string, string> = {
    low: '一般',
    medium: '重要',
    high: '紧急',
  };
  return priorityMap[priority] || priority;
};

// 事件处理函数
const handleSearch = () => {
  pagination.current = 1;
  console.log('搜索条件:', searchForm);
};

const handleReset = () => {
  Object.assign(searchForm, {
    roomNumber: '',
    type: '',
    status: '',
  });
  pagination.current = 1;
};

const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
};

const handleView = (record: any) => {
  message.info(`查看任务：${record.roomNumber}`);
};

const handleAssign = (record: any) => {
  message.success(`已分派任务给 ${record.assignedTo}`);
};

const handleStart = (record: any) => {
  message.success(`开始执行清洁任务：${record.roomNumber}`);
};

const handleComplete = (record: any) => {
  message.success(`清洁任务已完成：${record.roomNumber}`);
};

// 初始化
onMounted(() => {
  console.log('清洁任务管理页面已加载');
});
</script>

<template>
  <div class="cleaning-tasks">
    <div class="page-header">
      <h2>清洁任务管理</h2>
      <Button type="primary" @click="showAddModal = true">
        <IconifyIcon icon="ant-design:plus-outlined" />
        新建任务
      </Button>
    </div>

    <!-- 搜索表单 -->
    <Card :bordered="false" class="search-card">
      <Form :model="searchForm" layout="inline">
        <FormItem label="房间号">
          <Input
            v-model:value="searchForm.roomNumber"
            placeholder="请输入房间号"
            style="width: 120px"
          />
        </FormItem>
        <FormItem label="清洁类型">
          <Select
            v-model:value="searchForm.type"
            placeholder="请选择类型"
            style="width: 140px"
            allow-clear
          >
            <SelectOption value="regular">定期清洁</SelectOption>
            <SelectOption value="checkout">退租清洁</SelectOption>
            <SelectOption value="deep">深度清洁</SelectOption>
            <SelectOption value="emergency">紧急清洁</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="任务状态">
          <Select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            style="width: 120px"
            allow-clear
          >
            <SelectOption value="pending">待处理</SelectOption>
            <SelectOption value="assigned">已分派</SelectOption>
            <SelectOption value="processing">进行中</SelectOption>
            <SelectOption value="completed">已完成</SelectOption>
            <SelectOption value="cancelled">已取消</SelectOption>
          </Select>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="handleSearch">
            <IconifyIcon icon="ant-design:search-outlined" />
            搜索
          </Button>
          <Button @click="handleReset" style="margin-left: 8px">
            <IconifyIcon icon="ant-design:reload-outlined" />
            重置
          </Button>
        </FormItem>
      </Form>
    </Card>

    <!-- 统计卡片 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="总任务数"
          :value="statistics.totalTasks"
          color="#1890ff"
          icon="ant-design:file-text-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="待处理"
          :value="statistics.pendingTasks"
          color="#ff4d4f"
          icon="ant-design:clock-circle-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="进行中"
          :value="statistics.processingTasks"
          color="#faad14"
          icon="ant-design:sync-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="已完成"
          :value="statistics.completedTasks"
          color="#52c41a"
          icon="ant-design:check-circle-outlined"
        />
      </Col>
    </Row>

    <!-- 任务列表 -->
    <Card :bordered="false" class="table-card">
      <Table
        :columns="columns"
        :data-source="filteredTasks"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <Tag :color="getTaskStatusColor(record.status)">
              {{ getTaskStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'type'">
            <Tag :color="getTaskTypeColor(record.type)">
              {{ getTaskTypeText(record.type) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'priority'">
            <Tag :color="getPriorityColor(record.priority)">
              {{ getPriorityText(record.priority) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="handleView(record)">
                查看
              </Button>
              <Button
                v-if="record.status === 'pending'"
                type="link"
                size="small"
                @click="handleAssign(record)"
              >
                分派
              </Button>
              <Button
                v-if="record.status === 'assigned'"
                type="link"
                size="small"
                @click="handleStart(record)"
              >
                开始
              </Button>
              <Button
                v-if="record.status === 'processing'"
                type="link"
                size="small"
                @click="handleComplete(record)"
              >
                完成
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>
  </div>
</template>

<style scoped>
.cleaning-tasks {
  padding: 16px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.search-card {
  margin-bottom: 24px;
}

.statistics-row {
  margin-bottom: 24px;
}

.table-card {
  margin-bottom: 24px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 600;
  background-color: #fafafa;
}
</style>
